﻿using Automation.BDaq;
using PerpheralDevice.Units;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YamlDotNet.Serialization.TypeInspectors;

namespace PerpheralDevice.Advantech;

/// <summary>
/// 研华板卡 输出开关(应用读写开关)
/// </summary>
public class AdvantechSwitchRW : SwitchRW {

    private readonly ushort mfMacAddr;
    private readonly InstantDoCtrl mfInstantDoCtrl;
    public override string UnitID { get; }
    public AdvantechSwitchRW(PerpDev perpDev, InstantDoCtrl instantDoCtrl, int macAddr) {
        this.PerpDev = perpDev;
        this.mfMacAddr = (ushort)macAddr;
        this.UnitID = this.mfMacAddr.ToString();
        this.mfInstantDoCtrl = instantDoCtrl;

        this.TestIndex = Interlocked.Increment(ref PerpDevUnit.mfTestIndex);
    }

    public override SwitchRW View() {
        if (this.PerpDev.IsMocking) {
            return this.MockView();
        }

        int port = this.mfMacAddr / 8;
        int bitIndex = this.mfMacAddr % 8;
        mfInstantDoCtrl.ReadBit(port, bitIndex, out byte bitVal);
        // 高电平有效
        bool tempIsOpen = bitVal > 0;
        if (tempIsOpen != this.IsOpen) {
            this.IsOpen = tempIsOpen;
            this.OnStatusChangedRaise();
        }

        return this;
    }

    public override SwitchRW Open() {
        AppFramework.Logger.ILogger.Default.Info($"{this.GetType().FullName}:{this.PerpDev.PerpDevName}=>{nameof(Open)}({this.TestIndex})");
        if (this.PerpDev.IsMocking) {
            return this.MockOpen();
        } 

        int port = this.mfMacAddr / 8;
        int bitIndex = this.mfMacAddr % 8;
        // 高电平有效           
        this.mfInstantDoCtrl.WriteBit(port, bitIndex, 1);

        return this;
    }

    public override SwitchRW Shut() {
        AppFramework.Logger.ILogger.Default.Info($"{this.GetType().FullName}:{this.PerpDev.PerpDevName}=>{nameof(Shut)}({this.TestIndex})");
        if (this.PerpDev.IsMocking) {
            return this.MockShut();
        }

        int port = this.mfMacAddr / 8;
        int bitIndex = this.mfMacAddr % 8;
        // 高电平有效           
        this.mfInstantDoCtrl.WriteBit(port, bitIndex, 0);

        return this;
    }

}
